package com.cocotingo.snail.dispatcher;

import java.util.ArrayList;
import java.util.List;

public class ReusableThreadPool {
	
	private final List<ReusableThread> pool;
	private final int priority;
	private static int thread_gen_count = 0;
	
	public ReusableThreadPool() {
		this(Thread.NORM_PRIORITY);
	}
	
	public ReusableThreadPool(int priority) {
		this.priority = priority;
		pool = new ArrayList<ReusableThread>(4);
	}
	
	public synchronized void execute(Runnable target) {
		// get an available thread
		ReusableThread rt = null;
		for (ReusableThread t : pool) {
			if (t.getState() == ReusableThread.READY) {
				rt = t;
				break;
			}
		}
		// increase pool capacity
		if (rt == null) {
			final int n = 4;
			for (int i = 0; i < n; i++) {
				thread_gen_count++;
				rt = new ReusableThread(String.format("ReusableThread-%d", thread_gen_count), priority);
				pool.add(rt);
			}
		}
		// execute
		rt.execute(target);
	}
	
	public synchronized void drain() {
		for (ReusableThread t : pool) {
			t.dispose();
		}
		pool.clear();
	}

}
